<template>
  <top-area></top-area>
  <div id="map"></div>
  <RouterView />
  <bottom-area></bottom-area>
  <div class="btn">
    <button @click="handleDirection">导航</button>
  </div>
</template>

<script setup>
import TopArea from './components/TopArea.vue';
import BottomArea from './components/BottomArea.vue';
import mapboxgl from 'mapbox-gl'
import { onMounted, ref, provide } from 'vue'
import { Scene } from '@antv/l7';
import { Mapbox } from '@antv/l7-maps';
import useControl from './hooks/useControl';
import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions'
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css'
const map = ref(null)
const scene = ref(null)
const isDirection = ref(false)
let handleDirection

onMounted(() => {
  mapboxgl.accessToken = import.meta.env.VITE_TOKEN
  // 创建map实例
  map.value = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/dark-v11',
    center: [114.299, 30.585],
    zoom: 1,
    projection: 'globe',
  })
  // 创建场景实例
  scene.value = new Scene({
    id: 'map',
    map: new Mapbox({
      mapInstance: map.value
    }),
    logoVisible: false
  })
  //添加雾化效果 这个效果 跟中心点位置关联
  //采用了Hsl的颜色值 改变的是lightness值 越靠近中心点 越暗 越靠远中心点 越亮
  map.value.on('load', function () {
    fog()
  })
  map.value.on('move', fog)
  function fog() {
    let center = map.value.getCenter()
    map.value.setFog({
      color: `hsl(0,0%,${Math.abs(center.lng) / 360})`,
      'high-color': `hsl(0,0%,${Math.abs(center.lng) / 360})`,
    })
  }
  //添加一批控件 封装成一个单独的函数
  useControl(scene.value, map.value)

  // 添加导航插件
  const directions = new MapboxDirections({
    accessToken: import.meta.env.VITE_TOKEN,
  })

  handleDirection = () => {
    isDirection.value = !isDirection.value
    if (isDirection.value) {
      map.value.addControl(directions, 'top-left')
    } else {
      map.value.removeControl(directions)
    }
  }
  // 在App.vue根组件中注入实例map和scene
  provide('mapScene', {
    map: map.value,
    scene: scene.value
  })
})
</script>


<style scoped>
#map {
  width: 100vw;
  height: 100vh;
}

.btn {
  position: fixed;
  bottom: 50px;
  left: 10px;

  button {
    padding: 10px 20px;
  }
}
</style>
